<template>
  <div class="app-container  course postscript">
    <div class="edit-title-line">基本信息</div>
    <div>
      <div class="ele-form-item">
        <div class="ele-form-label">备课标题：</div>
        <div class="ele-form-content" :title="courseDetail.title">{{limitTitleLength(courseDetail.title)}}</div>
      </div>
      <div class="ele-form-item">
        <div class="ele-form-label">创建人：</div>
        <div class="ele-form-content">{{courseDetail.createBy}}</div>
      </div>
      <div class="ele-form-item">
        <div class="ele-form-label">学科：</div>
        <div class="ele-form-content">{{courseDetail.subjectName}}</div>
      </div>
      <div class="ele-form-item">
        <div class="ele-form-label">年级：</div>
        <div class="ele-form-content">{{courseDetail.gradeName}}</div>
      </div>
      <div class="ele-form-item">
        <div class="ele-form-label">班级：</div>
        <div class="ele-form-content">{{ courseDetail.classNameList.join(",")}}</div>
      </div>
    </div>
    <el-form ref="addPostScriptForm" :model="addPostScriptForm" :rules="addPostScriptFormRules" >
      <div>
        <el-form-item label="标题：" class="normal-form-item" prop="postscriptTitle" >
          <el-input v-model="addPostScriptForm.postscriptTitle"
                    @focus="clearFormValidate('postscriptTitle')"
                    maxLength="30"
                    class="width-300"
                    size="small"></el-input>
        </el-form-item>
      </div>
    </el-form>

    <div class="edit-title-line postscript-add-content">
      <span>后记内容</span>
      <span v-show="noPostScriptContent" class="form-warn">必填项，请填写！ </span>
    </div>
    <div>
      <editor-bar v-model="addPostScriptForm.postscriptContent.editor"
                 :height="600"
      ></editor-bar>
    </div>
    <div style="margin-top: 20px">
        <el-button type="primary" style="margin-right: 20px"  @click="commitAddPostScriptForm">保存</el-button>
        <el-button @click="cancelConfirm=true">取消</el-button>
    </div>
    <el-confirm-dialog
      elTip="确定要取消吗，若取消当前信息将不会保存？"
      :showDialog="cancelConfirm"
      :confirmSubmit="elConfirmDialogSubmit"
      :confirmCancel="elConfirmDialogCancel"
      @closeDialog = "elConfirmDialogClose"
    >
    </el-confirm-dialog>
  </div>
</template>

<script>
  import ElConfirmDialog from '@/components/ElConfirmDialog/index.vue'
  import EditorBar from '@/components/Tinymce'
  import {getPlLessonDetail, saveOrUpdatePostscript, getPostscriptDetail} from '@/api/api.js'
  export default {
        name: "postscriptEdit",
      components: {
        ElConfirmDialog,
        EditorBar
      },
        data () {
          return {
            cancelConfirm: false,
            courseDetail: {
              title: '',
              createName : '',
              subjectName : '',
              gradeName: '',
              classNameList : [],
              postscriptTitle : '',
              updateAt : '',
              postscriptContent : ''
            },
            noPostScriptContent: false,
            subjectTypeList: [],
            addPostScriptForm : {
              id: '',
              lessonId : '',
              postscriptTitle: '', //后记标题
              postscriptContent: {
                editor: '',
                isClear: false,
              }
            },
            addPostScriptFormRules :{
              postscriptTitle : [
                { required: true, message: '必填项，请填写！', trigger: 'blur' },
                { max: 30, message: '最多 30 个字符', trigger: 'blur' }
              ]
            }
          }
        },
      methods: {
          formatSubjectByType(code) {
            for (let item of this.subjectTypeList) {
              if (item.code === code ) {
                return item.label;
              }
            }
            return "";
          },
          formatClassList(classList) {
            if (classList instanceof Array) {
              return classList.join("、")
            }
            return classList
          },
        /** 取消询问框相关**/
        elConfirmDialogSubmit() {
          this.cancelConfirm = false
          this.$router.go(-1)
        },
        elConfirmDialogCancel() {
          this.cancelConfirm = false
        },
        elConfirmDialogClose() {
          this.cancelConfirm = false
        },
        /** 表单提交 **/
        commitAddPostScriptForm() {
          this.$refs.addPostScriptForm.validate((valid) => {
            if (valid) {
              console.log(this.addPostScriptForm.postscriptContent.editor)
              if(!this.addPostScriptForm.postscriptContent.editor || !this.validateContentByRemoveTag(this.addPostScriptForm.postscriptContent.editor)) {
                this.noPostScriptContent = true
                this.$alert("输入有误，请检查", "提示", {type : "warning"})
                return;
              }
              let params = {
                id : this.addPostScriptForm.id,
                title : this.addPostScriptForm.postscriptTitle,
                lessonId: this.addPostScriptForm.lessonId,
                content : this.addPostScriptForm.postscriptContent.editor
              }
              saveOrUpdatePostscript(params).then(res => {
                console.log(res)
                if (res.code === 200) {
                  this.$alert("修改成功！", "提示", {type : "success",
                    callback : () => {
                      this.$router.push({path : "/postscript/list"})
                    }
                  })
                } else {
                  this.$alert("修改失败！" + res.message, "错误", {type : "error"})
                }
              })
            } else {
              if(!this.addPostScriptForm.postscriptContent.editor) {
                this.noPostScriptContent = true
              }
              this.$alert("输入有误，请检查", "提示", {type : "warning"}).then(() => {
                this.noPostScriptContent = false
              })
            }
          })
        },
        /** 表单提交结束 **/
       //标题长度限制
        limitTitleLength(title) {
          if (!title) {
            return ""
          } else if (title.length <= 10) {
            return title
          } else {
            let tempTitle = title.substr(0, 10)
            return `${tempTitle}……`
          }
        },
        formatClassNameList(classNameList) {
          if (!classNameList || !Array.isArray(classNameList)) {
            return []
          }

          let tempClassNameArr = []
          classNameList.forEach(item => {
            tempClassNameArr.push(`${item.classCode}班`)
          })
          return tempClassNameArr
        },
        //获取备课详情
        getCourseDetail(){
          let lessonId = this.$route.query.lessonId
          let params = {
            plLessonId : lessonId
          }
          getPlLessonDetail(params).then(res => {
            if (res.code == 200) {
              this.courseDetail.title = res.result.title
              this.courseDetail.createBy = res.result.createName
              this.courseDetail.subjectName = res.result.subjectName
              this.courseDetail.gradeName = ( res.result.classList && Array.isArray(res.result.classList) && res.result.classList.length > 0) ?  res.result.classList[0].gradeName : ''
              this.courseDetail.classNameList =  ( res.result.classList && Array.isArray(res.result.classList) && res.result.classList.length > 0) ? this.formatClassNameList(res.result.classList) : []
            // console.log(this.courseDetail.classNameList)
            } else {
              this.$alert("获取后记详情失败！" + res.message, "错误", {type : "error"})
            }
          })
        },
        /**清除校验**/
        clearFormValidate(prop) {
          this.$refs.addPostScriptForm.clearValidate(prop)
        },
        handleOnfocusEditor() {
          this.noPostScriptContent = false
        },
        //校验除去html标签后是否还有内容
        validateContentByRemoveTag(str) {
          if (!str) {
            return false
          }

          let res = str.replace(/<[^>]+>/g,"")
          if (!res){
            return false;
          }
          res = res.replace(/ /ig,"")
          if(!res) {
            return false;
          }
          res = res.replace(/<br>/g,"");
          if (!res) {
            return false;
          }

          res = res.replace(/&nbsp;/g,"")
          if(!res){
            return false
          }
          return true;

        },
        //获取后记详情

        formatClassList(classList) {
          if (classList && classList instanceof Array && classList.length > 0) {
            this.courseDetail.grade = classList[0].gradeName
            let classStr = ""
            classList.forEach(item => classStr =   classStr + item.classCode + "班， ")
            let length = classStr.length - 2
            return classStr.substr(0, length)
          }
          return null
        },

        getPostScriptDetail() {
          let params = {
             lessonId: this.$route.query.lessonId,
             postscriptId : this.$route.query.postscriptId
          }
          getPostscriptDetail(params).then(res => {
           if (res.code  == 200) {
             this.addPostScriptForm.id = this.$route.query.postscriptId
             this.addPostScriptForm.lessonId = this.$route.query.lessonId
             this.addPostScriptForm.postscriptTitle = res.result.title
             this.addPostScriptForm.postscriptContent.editor = res.result.content
           } else {
             this.$alert("当前备课后记不存在！", "提示", {type : "error",
               callback : () => {
                 this.$router.push({path : "/postscript/list"})
               }
             })
           }
          })
        }
      },
      mounted () {
        this.getPostScriptDetail()
        this.getCourseDetail()
      },
      created() {

      }
    }
</script>

<style scoped>

</style>
